function bindElements(){

	//bind submit button
	$("#Submit").bind('click', function(){
		if( validateElements() ){
			//closer function to make sure all inserts are completed.
			var insertBeneficary = function(){
				var beneficary_count = $("input[id='First']:not(table[id='protoHTML'] #First)");
				var obj = {};
				$.each( beneficary_count, function(i, n){
					obj = {
						'Address1' : $("input[id='Address1']:not(table[id='protoHTML'] #Address1):eq("+i+")").val(),
						'Address2' : $("input[id='Address2']:not(table[id='protoHTML'] #Address2):eq("+i+")").val(),
						'CellPhone' : $("input[id='CellPhone']:not(table[id='protoHTML'] #CellPhone):eq("+i+")").val(),
						'City' : $("input[id='City']:not(table[id='protoHTML'] #City):eq("+i+")").val(),
						'Email': $("input[id='Email']:not(table[id='protoHTML'] #Email):eq("+i+")").val(),
						'EmpID' : $("input[id='EmpID']:not(table[id='protoHTML'] #EmpID):eq(0)").val(),//only need the first empID
						'First' : $("input[id='First']:not(table[id='protoHTML'] #First):eq("+i+")").val(),
						'HomePhone' : $("input[id='HomePhone']:not(table[id='protoHTML'] #HomePhone):eq("+i+")").val(),
						'Last' : $("input[id='Last']:not(table[id='protoHTML'] #Last):eq("+i+")").val(),
						'PhonePrimaryID' : $("select[id='PhonePrimaryID']:not(table[id='protoHTML'] #PhonePrimaryID):eq("+i+") option:selected").val(),
						'RelationID' : $("select[id='RelationID']:not(table[id='protoHTML'] #RelationID):eq("+i+") option:selected").val(),
						'State' : $("select[id='State']:not(table[id='protoHTML'] #State):eq("+i+") option:selected").val(),
						'StepID' : $("input[id='StepID']:not(table[id='protoHTML'] #StepID):eq(0)").val(),//only need the first stepID
						'WorkPhone' : $("input[id='WorkPhone']:not(table[id='protoHTML'] #WorkPhone):eq("+i+")").val(),
						'WorkPhoneExt' : $("input[id='WorkPhoneExt']:not(table[id='protoHTML'] #WorkPhoneExt):eq("+i+")").val(),
						'Zip' : $("input[id='Zip']:not(table[id='protoHTML'] #Zip):eq("+i+")").val()
					};
					submitForm(obj, 'insert_step3_employee_beneficaries', false, function(){return false;}, function(){return false;}, function(){return false;});
				});
			};
			
			//javascript closer message and timeout
			var step4Complete = function(){							
				document.location.href='step3-orientation4.cfm?StepID=' + $("#StepID").val() + '&EmpID=' + $("#EmpID").val();
				clearTimeout(timeout_index);
				delete timeout_index;
			};
			
			//setting javascript closer to timeout. 
			timeout_index = setTimeout(step4Complete, insertBeneficary()); 	
			
		}
		return false;
	});
	
	//bind skip >> button
	$("#Skip").bind('click', function(){
		document.location.href='step3-orientation4.cfm?StepID=' + $("#StepID").val() + '&EmpID=' + $("#EmpID").val();
	});
	
	//binds CLICK HERE link to add more beneficaries
	$("#more_beneficiaries").bind('click', function(){
		var tableCopy = function(){
			var element_count = $("input[id='First']").length;
			var html = function(){
				var table = '<span id="protoTable_' + element_count +'"><hr /><div>' +
				'<a href="#" class="tablemod" id="protoLink_' + element_count + '"';
				var remove_script = '$("#protoTable_' + element_count + '").remove();return false;';
				table = table + " onclick='" + remove_script + "'>Delete Record</a>";
				table = table + '</div>' + $("#protoHTML").html() + '</span>';
				return table;
			};			
			return html;
		};
		$('#beneficiary_body').append( tableCopy() );	
		return false;
	});

}


var validateElements = function(){
	//sets error count to zero, if greater then zero, some data is not valid
	var error_count = 0;

	//var for required element error message.  A custom message can 
	//be set on the input element called error_message
	var require_message = function(id){		
		return $("#" + id).attr('error_message');	
	}
	
	//these fields are require on form.
	var required_fields = ['First', 'Last'];
	
	//these fields are phone number fields
	var phone_fields = ['HomePhone', 'CellPhone', 'WorkPhone'];	
	
	//regex validators
	var re_phone = /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/;
	
	//removes error messages from previous validation.
	$(".ui-state-error").removeClass();
	
	//creates html of errors
	var html_errors = function(){
		var error_link = "";		
		//if fields in the required_fields variable are empty this error is triggered.	checking for dob also.
		$.map(required_fields,function(field){
			var field_string = "input[id='" + field + "']:not(table[id='protoHTML'] #" + field + ")";
			$.each( $(field_string), function(i, n){
				if( !$(n).val() ) {
					error_count++;
					$(n).addClass('ui-state-error');
					error_link = error_link + "<span class='link_error'" + "id='error_link_" + i + "_" + n.id + "'>" + 
					n.id + ":</span> " + require_message(n.id) + "<br />";			
				}
			});
		});
		
		//phone number format check, error is triggered if phone is malformed
		$.map(phone_fields, function(field){
			var field_string = "input[id='" + field + "']:not(table[id='protoHTML'] #" + field + ")";
			$.each( $(field_string), function(i, n){
				if( $(n).val() && !$(n).val().match(new RegExp(re_phone)) ){
					error_count++;
					$(n).addClass('ui-state-error');
					error_link = error_link + "<span class='link_error'" + "id='error_link_" + i + "_" + n.id + "'>" + 
					n.id + ":</span> " + require_message(n.id) + "<br />";
				}
			});
			
		});
				
		return error_link;
	};
	
	//creates jquery ui dialog box html
	$("div.entry").append('<div id="error_dialog" style="width: auto;"><p>' + html_errors() + '</p></div>');
	
	//creates jquery ui dialog box object
	var $error_dialog = $('#error_dialog').dialog({//jquery notation.  Shorthand for calling object.
		autoOpen: false, width: 'auto', modal: true, title: 'The following fields have errors', resizable: false,
		open: function(event, ui) { $("div.ui-dialog-titlebar").width( $(".ui-dialog").width() ); },
		close: function(event, ui) {$(this).dialog( "destroy" ) }
	});

	//if no errors in validation, well... the data is valid!
	if(error_count){
		$error_dialog.dialog('open');
		$("span[id^='error_link_']").click(function(){
			var element_id = "input[id='" + 
				this.id.split("_")[3] + "']:eq(" + this.id.split("_")[2] + ")";			
			$.scrollTo(element_id);//jquery pluging ScrollTo
			$error_dialog.dialog('close');
			$(element_id).focus();
		});
		return false;
	}else{return true;}
};



//ajax POST to add to database.
function submitForm(obj, api, id, successFunc, completeFunc, errorFunc){	
	var api_url = "api.cfm?api=" + api + ( (id) ? "&id=" + id : "" );
	$.ajax({
		type:'POST', url:api_url, dataType: 'json', async: false, data: obj,
		success: function(json) { successFunc },
		complete: function(){ completeFunc },
		error: function(){ errorFunc }
	});
}



//ajax data get
var getData = function(api, id, successFunc, completeFunc, errorFunc){
	var data = "";
	var api_url = "api.cfm?api=" + api + "&" + id;	
	$.ajax({
		type:'GET', url:api_url, dataType: 'json', async: false,
		success: function(json){ data = json; },
		complete: function(){ completeFunc },
		error: function(){ errorFunc }
	});
	return data;
};



$(function(){
	bindElements();
});